﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace EpiNEXT.WPF
{
    public abstract class OrientableListSelector : ListBox
    {
        public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register("Orientation", typeof(Orientation), typeof(OrientableListSelector), new PropertyMetadata(Orientation.Vertical));

        public Orientation Orientation
        {
            get
            {
                return (Orientation)this.GetValue(OrientationProperty);
            }
            set
            {
                this.SetValue(OrientationProperty, value);
            }
        }

        protected override void OnGotFocus(RoutedEventArgs e)
        {
            base.OnGotFocus(e);

            ListCollectionView vm = this.ItemsSource as ListCollectionView;

            DependencyObject dep1 = VisualTreeHelper.GetChild(e.OriginalSource as DependencyObject, 0);
            DependencyObject dep2 = VisualTreeHelper.GetChild(dep1 as DependencyObject, 0);
            DependencyObject dep3 = VisualTreeHelper.GetChild(dep2 as DependencyObject, 0);

            if (dep3 is WrapPanel)
            {
                for (int i = 0; i < VisualTreeHelper.GetChildrenCount(dep3); i++)
                {
                    ListBoxItem listItem = (VisualTreeHelper.GetChild(dep3 as DependencyObject, i) as ListBoxItem);
                    EpiNEXT.Core.CodeListValue listValue = vm.CurrentItem as EpiNEXT.Core.CodeListValue;

                    if (listValue.Equals(listItem.Content))
                    {
                        listItem.Focus();
                    }
                }
            }
        }
    }
}
